﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Bluno.Core
{
    public class PlanProtocol
    {
        private const string PARSE_REGEX = @"(#(?'address'\d+)){0,1}(<(?'command'\w+)>)(,{0,1}(?'contents'\d+))*;";
        public int? Address { get; set; }
        public string Command { get; set; }
        public List<int> Contents { get; set; }
        //public bool IsAddressEnabled { get; set; }
        public PlanProtocol()
        {
            //IsAddressEnabled = false;
            Contents = new List<int>();
            Address = null;
        }
        public static PlanProtocol Parse(string value)
        {
            var tmp = System.Text.RegularExpressions.Regex.Matches(value, PARSE_REGEX);
            if (tmp.Count != 1)
            {
                throw new InvalidOperationException("value parse failed");
            }
            PlanProtocol result = new PlanProtocol();
            var match = tmp[0];
            result.Command = match.Groups["command"].Value;
            if (match.Groups["address"].Success)
            {
                result.Address = int.Parse(match.Groups["address"].Value);
                //result.IsAddressEnabled = true;
            }
            if (match.Groups["contents"].Success)
            {
                var contentGroup = match.Groups["contents"];
                for (int i = 0; i < contentGroup.Captures.Count; i++)
                {
                    result.Contents.Add(int.Parse(contentGroup.Captures[i].Value));
                }
            }

            return result;
        }
        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();
            if (Address.HasValue)
            {
                sb.AppendFormat("#{0}", Address.Value);
            }
            sb.AppendFormat("<{0}>", Command);

            sb.Append(string.Join<int>(",", Contents));


            sb.Append(";");
            return sb.ToString();
        }
    }
}
